package com.gh.ggkt.vod.service.impl;

import com.atguigu.ggkt.model.vod.*;
import com.atguigu.ggkt.vo.vod.CourseFormVo;
import com.atguigu.ggkt.vo.vod.CoursePublishVo;
import com.atguigu.ggkt.vo.vod.CourseQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gh.ggkt.vod.mapper.CourseMapper;
import com.gh.ggkt.vod.mapper.SubjectMapper;
import com.gh.ggkt.vod.mapper.TeacherMapper;
import com.gh.ggkt.vod.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Eric Fang
 * @since 2022-09-11
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private SubjectMapper subjectMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private CourseDescriptionService descriptionService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private VodService vodService;
    @Override
    public Map<String, Object> findPageCourse(Page<Course> pageParam, CourseQueryVo courseQueryVo) {
        //课程专业ID
        Long subjectId = courseQueryVo.getSubjectId();
        //课程讲师ID
        Long teacherId = courseQueryVo.getTeacherId();
        //课程标题
        String title = courseQueryVo.getTitle();
        //课程专业父级ID
        Long subjectParentId = courseQueryVo.getSubjectParentId();
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(title)) {
            queryWrapper.like(Course::getTitle, title);
        }
        if (teacherId != null) {
            queryWrapper.eq(Course::getTeacherId, teacherId);
        }
        if (subjectId != null) {
            queryWrapper.eq(Course::getSubjectId, subjectId);
        }
        if (subjectParentId != null) {
            queryWrapper.eq(Course::getSubjectParentId, subjectParentId);
        }
        Page<Course> coursePage = baseMapper.selectPage(pageParam, queryWrapper);
        long totalCount = coursePage.getTotal();//总记录数
        long totalPage = coursePage.getPages();//总页数
        List<Course> records = pageParam.getRecords();
        records.forEach(course -> {
            getTeacherOrSubjectName(course);
        });
        Map<String, Object> map = new HashMap<>();
        map.put("totalCount", totalCount);
        map.put("totalPage", totalPage);
        map.put("records", records);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long saveCourseInfo(CourseFormVo courseFormVo) {
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo, course);
        baseMapper.insert(course);
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(course.getId());
        courseDescription.setDescription(courseFormVo.getDescription());
        descriptionService.save(courseDescription);
        return course.getId();
    }

    /**
     * 通过id查询课程信息
     *
     * @param id
     * @return
     */
    @Override
    public CourseFormVo getCourseInfoById(Long id) {
        Course course = baseMapper.selectById(id);
        if (course == null) {
            return null;
        }
        CourseFormVo courseFormVo = new CourseFormVo();
        BeanUtils.copyProperties(course, courseFormVo);
        CourseDescription courseDescription = descriptionService.getById(id);
        courseFormVo.setDescription(courseDescription.getDescription());
        return courseFormVo;
    }

    /**
     * 修改课程信息
     *
     * @param courseFormVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCourseInfo(CourseFormVo courseFormVo) {
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo, course);
        baseMapper.updateById(course);
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(courseFormVo.getId());
        courseDescription.setDescription(courseFormVo.getDescription());
        descriptionService.updateById(courseDescription);
    }

    @Override
    public CoursePublishVo getCoursePublishVo(Long id) {
        CoursePublishVo coursePublishVo = teacherMapper.getCoursePublishVo(id);
        return coursePublishVo;
    }

    /**
     * 课程最终发布
     *
     * @param id
     */
    @Override
    public void publishCourse(Long id) {
        Course course = baseMapper.selectById(id);
        course.setStatus(1);
        course.setPublishTime(new Date());
        baseMapper.updateById(course);
    }

    /**
     * 删除课程
     *
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeCourse(Long id) {
        //删除课程
        baseMapper.deleteById(id);
        //删除课程描述
        descriptionService.removeById(id);
        //删除章节
        LambdaQueryWrapper<Chapter> chapterQueryWrapper = new LambdaQueryWrapper<>();
        chapterQueryWrapper.eq(Chapter::getCourseId, id);
        chapterService.remove(chapterQueryWrapper);
        //删除小节
        //根据课程id查询出课程里的所有小节
        LambdaQueryWrapper<Video> videoQueryWrapper = new LambdaQueryWrapper<>();
        videoQueryWrapper.eq(Video::getCourseId, id);
        List<Video> videoList = videoService.list(videoQueryWrapper);
        videoList.forEach(video -> {
            //根据小节获取到视频id
            String sourceId = video.getVideoSourceId();
            if(StringUtils.isNotEmpty(sourceId)){
                vodService.removeVideo(sourceId);
            }
        });
        //根据课程id删除小节
        videoService.remove(videoQueryWrapper);
    }

    @Override
    public List<Course> findByKeyword(String keyword) {
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Course::getTitle,keyword);
        List<Course> courseList = baseMapper.selectList(queryWrapper);
        return courseList;
    }

    /**
     * 获取讲师和分类名称
     *
     * @param course
     */
    public Course getTeacherOrSubjectName(Course course) {
        Long teacherId = course.getTeacherId();
        Teacher teacher = teacherMapper.selectById(teacherId);
        if (teacher != null) {
            course.getParam().put("teacherName", teacher.getName());
        }
        Subject subjectOne = subjectMapper.selectById(course.getSubjectParentId());
        if (subjectOne != null) {
            course.getParam().put("subjectParentTitle", subjectOne.getTitle());
        }
        Subject subjectTwo = subjectMapper.selectById(course.getSubjectId());
        if (subjectTwo != null) {
            course.getParam().put("subjectTitle", subjectTwo.getTitle());
        }
        return course;
    }
}
